<?php

namespace backend\controllers;

use Yii;
use yii\JPush\Client;

use yii\data\Pagination;
use backend\models\Realname;
use backend\models\User;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * RealnameController implements the CRUD actions for Realname model.
 */
class RealnameController extends BaseController
{
	public $layout = "lte_main";

    /**
     * Lists all Realname models.
     * @return mixed
     */
    public function actionIndex()
    {
        $query = Realname::find()->where(['is_shenhe' => 0]);
         $querys = Yii::$app->request->get('query');
        if(count($querys) > 0){
            $condition = "";
            $parame = array();
            foreach($querys as $key=>$value){
                $value = trim($value);
                if(empty($value) == false){
                    $parame[":{$key}"]=$value;
                    if(empty($condition) == true){
                        $condition = " {$key}=:{$key} ";
                    }
                    else{
                        $condition = $condition . " AND {$key}=:{$key} ";
                    }
                }
            }
            if(count($parame) > 0){
                $query = $query->where($condition, $parame);
            }
        }

        $pagination = new Pagination([
            'totalCount' =>$query->count(), 
            'pageSize' => '10', 
            'pageParam'=>'page', 
            'pageSizeParam'=>'per-page']
        );
        
        $orderby = Yii::$app->request->get('orderby', '');
        if(empty($orderby) == false){
            $query = $query->orderBy($orderby);
        }


        $models = $query
        ->offset($pagination->offset)
        ->limit($pagination->limit)
        ->all();
//        print_r($models);
        return $this->render('index', [
            'models'=>$models,
            'pages'=>$pagination,
            'query'=>$querys,
        ]);
    }

    /**
     * Displays a single Realname model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        $model = $this->findModel($id);
        echo json_encode($model->getAttributes());

    }

    /**
     * Creates a new Realname model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Realname();
        if ($model->load(Yii::$app->request->post())) {
        
        
            if($model->validate() == true && $model->save()){
                $msg = array('errno'=>0, 'msg'=>'保存成功');
                echo json_encode($msg);
            }
            else{
                $msg = array('errno'=>2, 'data'=>$model->getErrors());
                echo json_encode($msg);
            }
        } else {
            $msg = array('errno'=>2, 'msg'=>'数据出错');
            echo json_encode($msg);
        }
    }

    /**
     * Updates an existing Realname model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate()
    {
        $id = Yii::$app->request->post('id');
        $model = $this->findModel($id);
        $userId = $model['user_id'];
        $model1 = User::find()->where(['user_id' => $userId])->one();
//        print_r($model1);
        $model1->is_realname = 2;
        $model1->is_anchor = 0;
        $model->is_shenhe = 1;

        $model->save();
        $model1->save();

            if($model->validate() == true && $model->save()){

                $client = new Client(Yii::$app->params['AppKey'],Yii::$app->params['MasterSecret']);

//                    var_dump($model->user_id);
                $alias = strval($userId);

//                    $client->device()->getAliasDevices(21003);
                $response = $client->push();
                $response->setPlatform('all');
//            $response->addTag(['tag1']);
                $response   ->setNotificationAlert('Hello, JPush');
//        $response->addAllAudience();
                $response->addAlias($alias);

                $response    ->iosNotification('通過實名認證！恭喜您距離主播還有壹步,加油！', [
                    'sound' => 'sound',
                    'badge' => '+1',
                    'extras' => [
//                        'type' => 0
                    ]
                ]);
//                $response    ->androidNotification('通過實名認證！恭喜您距離主播還有壹步,加油！', [
//                    'sound' => 'sound',
//                    'badge' => '+1',
//                    'extras' => [
////                            'type' => 0
//                    ]
//                ]);

                try {
                    $response->send();
                } catch (\JPush\Exceptions\JPushException $e) {
                    // try something else here
                    echo json_encode($e);
                }



                $msg = array('errno'=>0, 'msg'=>'保存成功');
                echo json_encode($msg);
            }
            else{
                $msg = array('errno'=>2, 'data'=>$model->getErrors());
                echo json_encode($msg);
            }
    }

    /**
     * Deletes an existing Realname model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete(array $ids)
    {
        if(count($ids) > 0){
            $c = Realname::deleteAll(['in', 'id', $ids]);
            echo json_encode(array('errno'=>0, 'data'=>$c, 'msg'=>json_encode($ids)));
        }
        else{
            echo json_encode(array('errno'=>2, 'msg'=>''));
        }


    }

    /**
     * Finds the Realname model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Realname the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Realname::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
